function ProtoMan () {
}

ProtoMan.prototype.decoder = new Array();

//注册消息解码器
ProtoMan.prototype.registerDecoder = function (id, func) {
    if (this.decoder[id] != null) {
        console.log("Find message decoder already exist, id = " + id);
        return;
    } else if (func == null) {
        console.log("Message decode function is null");
        return;
    }
        
    this.decoder[id] = func;
};

//解析messagepack包装的消息
ProtoMan.prototype.process = function(sock, clients, msg) {
    if (server.Debug) console.log(msg);

    if (Array.isArray(msg) && msg.length > 0) {
        if (typeof(msg[0]) == 'number') {
            
            var f = this.decoder[msg[0]];
            if (f == null) {
                console.log('Message without suitable decoder: ' + msg);
                console.log('Message id: ' + msg[0] + ' has not suitable decoder. Forget to registered?');
                return false;
            } else {
                return f(sock, msg);
            }
                
         }
        else {
            console.log('Message invalid, type is not integer. msg = ' + msg);
            return false;
        } 
    } else {
        console.log('Message invalid, content is empty OR message is not an array format.');
        return false;
    }
};

function broadcast(message, clients, sender) {
    for (var key in clients) {
        if (clients[key] != sender) {
            clients[key].write(message);
        }
    }
}

//exports.protoMan = new ProtoMan();
module.exports = new ProtoMan();
